<template>
  <div class="map-modal" v-if="visible">
    <div class="map-container">
      <div class="header">
        <h3>选择地址</h3>
        <span class="close-btn" @click="close">×</span>
      </div>
      
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchKeyword"
          placeholder="输入地址搜索"
          @keyup.enter="handleSearch"
        />
        <button 
          class="search-btn" 
          @click="handleSearch"
          :disabled="!searchKeyword"
        >
          搜索
        </button>
      </div>

      <div class="search-results" v-if="searchResults.length > 0">
        <div 
          v-for="result in searchResults" 
          :key="result.id"
          class="search-result-item"
          @click="selectSearchResult(result)"
        >
          <div class="result-name">{{ result.name }}</div>
          <div class="result-address">{{ result.address }}</div>
        </div>
      </div>

      <div ref="mapContainer" class="map"></div>

      <div class="footer">
        <div class="selected-address" v-if="currentAddress">
          当前选择: {{ currentAddress }}
        </div>
        <button 
          class="confirm-btn"
          :class="{ 'active': hasSelectedAddress }"
          :disabled="!hasSelectedAddress"
          @click="confirmAddress"
        >
          确定
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'

declare global {
  interface Window {
    AMap: any
  }
}

const props = defineProps<{
  visible: boolean
}>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  'select-address': [address: any]
}>()

const mapContainer = ref<HTMLElement | null>(null)
const searchKeyword = ref('')
const searchResults = ref<any[]>([])
const currentAddress = ref('')
const currentLocation = ref<any>(null)

const hasSelectedAddress = computed(() => {
  return !!(currentAddress.value && currentLocation.value)
})

let map: any = null
let marker: any = null

// 更新标记和地址
const updateLocation = (location: any, address: string) => {
  console.log('更新位置:', location, address)
  currentLocation.value = location
  currentAddress.value = address

  // 更新标记
  if (marker) {
    marker.setMap(null)
  }
  marker = new window.AMap.Marker({
    position: [location.lng, location.lat],
    map: map
  })
  map.setCenter([location.lng, location.lat])
}

// 初始化地图
const initMap = () => {
  console.log('开始初始化地图', mapContainer.value, window.AMap)
  if (!mapContainer.value || !window.AMap) {
    console.error('地图初始化失败：', {
      container: !!mapContainer.value,
      AMap: !!window.AMap
    })
    return
  }

  // 创建地图实例
  map = new window.AMap.Map(mapContainer.value, {
    zoom: 13,
    center: [116.397428, 39.90923]
  })
  console.log('地图实例创建成功', map)

  // 确保插件加载完成
  window.AMap.plugin(['AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Geocoder'], function() {
    // 添加定位控件
    const geolocation = new window.AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      buttonPosition: 'RB',
      buttonOffset: new window.AMap.Pixel(10, 20),
      zoomToAccuracy: true
    })
    map.addControl(geolocation)

    // 获取当前位置
    geolocation.getCurrentPosition((status: string, result: any) => {
      if (status === 'complete') {
        const { position } = result
        const geocoder = new window.AMap.Geocoder()
        geocoder.getAddress([position.lng, position.lat], (status: string, result: any) => {
          if (status === 'complete' && result.regeocode) {
            updateLocation(
              { lng: position.lng, lat: position.lat },
              result.regeocode.formattedAddress
            )
          }
        })
      }
    })

    // 添加点击事件
    map.on('click', (e: any) => {
      const lnglat = e.lnglat
      const geocoder = new window.AMap.Geocoder()
      geocoder.getAddress([lnglat.lng, lnglat.lat], (status: string, result: any) => {
        if (status === 'complete' && result.regeocode) {
          updateLocation(
            { lng: lnglat.lng, lat: lnglat.lat },
            result.regeocode.formattedAddress
          )
        }
      })
    })
  })
}

// 搜索地址
const handleSearch = () => {
  if (!searchKeyword.value || !window.AMap) return

  window.AMap.plugin(['AMap.PlaceSearch'], function() {
    const placeSearch = new window.AMap.PlaceSearch({
      citylimit: false,
      type: '',
      pageSize: 10,
      pageIndex: 1
    })

    placeSearch.search(searchKeyword.value, (status: string, result: any) => {
      console.log('搜索结果:', status, result)
      if (status === 'complete' && result.poiList && result.poiList.pois) {
        searchResults.value = result.poiList.pois.map((poi: any) => ({
          id: poi.id || Math.random().toString(),
          name: poi.name,
          address: poi.address || poi.name,
          location: poi.location
        }))
      } else {
        searchResults.value = []
        console.error('搜索失败:', status, result)
      }
    })
  })
}

// 选择搜索结果
const selectSearchResult = (result: any) => {
  console.log('选择搜索结果:', result)
  updateLocation(result.location, result.address)
  searchResults.value = []
  searchKeyword.value = ''
}

// 确认选择
const confirmAddress = () => {
  if (currentAddress.value && currentLocation.value) {
    console.log('确认地址:', {
      address: currentAddress.value,
      location: currentLocation.value
    })
    emit('select-address', {
      address: currentAddress.value,
      location: currentLocation.value
    })
    close()
  }
}

// 关闭弹窗
const close = () => {
  emit('update:visible', false)
  currentAddress.value = ''
  currentLocation.value = null
  searchKeyword.value = ''
  searchResults.value = []
  if (marker) {
    marker.setMap(null)
    marker = null
  }
}

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      if (!map) {
        initMap()
      }
    })
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (map) {
    map.destroy()
    map = null
  }
})
</script>

<style scoped>
.map-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.map-container {
  width: 100%;
  height: 100%;
  background: white;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding-bottom: 60px; /* 添加底部内边距，避免被购物车遮挡 */
}

.header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.close-btn:hover {
  color: #333;
}

.search-box {
  padding: 16px;
  display: flex;
  gap: 8px;
}

.search-box input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-btn {
  padding: 8px 16px;
  background: #4A90E2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.search-results {
  position: absolute;
  top: 120px;
  left: 16px;
  right: 16px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1;
}

.search-result-item {
  padding: 12px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.search-result-item:last-child {
  border-bottom: none;
}

.search-result-item:hover {
  background: #f5f5f5;
}

.result-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.result-address {
  font-size: 12px;
  color: #666;
}

.map {
  flex: 1;
  width: 100%;
  height: 100%;
  min-height: 300px;
  background: #f5f5f5;
}

.footer {
  padding: 16px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white; /* 确保底部背景是白色 */
  position: fixed; /* 固定在底部 */
  bottom: 60px; /* 与购物车保持距离 */
  left: 0;
  right: 0;
  z-index: 1001; /* 确保在地图上层 */
}

.selected-address {
  font-size: 14px;
  color: #666;
  flex: 1;
  margin-right: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.confirm-btn {
  padding: 8px 24px;
  background: #ccc;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: not-allowed;
  transition: all 0.3s ease;
}

.confirm-btn.active {
  background: #4A90E2;
  cursor: pointer;
}

.confirm-btn.active:hover {
  background: #357ABD;
}
</style> 